package com.msblearn.C_008;

import java.util.LinkedList;

public class T_MyContainer<T> {
    final private LinkedList<T> linkedList = new LinkedList<T>();
    final private int Max = 10;
    private int count = 0;

    public synchronized void put(T t) {
        //为啥用while而不用if.
        //不行。
        while (linkedList.size() == Max) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        linkedList.add(t);
        ++count;
        this.notifyAll();
    }

    public synchronized T get() {
        T t = null;
        while (linkedList.size() == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        t = linkedList.removeFirst();
        count--;
        this.notifyAll();
        return t;
    }

    public static void main(String[] args) {
        T_MyContainer<String> tt = new T_MyContainer<>();
        //启动消费者线程
        for (int i = 0; i < 8; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    System.out.println(tt.get());
                }
            }, "T" + i).start();
        }

        //启动生产者线程
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 23; j++) {
                    tt.put(Thread.currentThread().getName() + " " + j);
                }
            }, "TT").start();
        }
    }
}
